package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.DataBoard;
import com.ruoyi.system.domain.Forest.grm.AuthGRM;
import com.ruoyi.system.domain.Forest.grm.GRMData;
import com.ruoyi.system.domain.SysAlarm;
import com.ruoyi.system.domain.SysDataBoard;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.domain.cache.DeviceCache;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController("")
@RequestMapping("/data/board")
@Anonymous
@Slf4j
public class DataBoardController  extends BaseController {

    @Autowired
    private ISysAlarmService sysAlarmService;

    @Autowired
    private ISysDeviceService sysDeviceService;

    @Autowired
    private ISysDataBoardService sysDataBoardService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysBuildingService sysBuildingService;

    @Autowired
    private ISysHousingService sysHousingService;
    @GetMapping("/top/{deptId}")
    public AjaxResult top(@PathVariable("deptId") Long deptId){

        GRMData plcData = sysDataBoardService.loadPlcData(getDeptId());
        List<DataBoard> list = new ArrayList<>();
        Integer userCount = sysDeviceService.useDevice(deptId);
        //开栓户数
        list.add(new DataBoard("开栓户数",  userCount + "", "户"));
        //实供面积
        list.add(new DataBoard("实供面积", sysDeviceService.selectArea(deptId).toString(), "m²"));
        //供热功率
        list.add(new DataBoard("供热功率", String.valueOf(plcData.getPower()), "kW"));
        //耗热功率
        list.add(new DataBoard("耗电功率", plcData.getPowerConsumption() + "", "kW"));
        //室外温度
        list.add(new DataBoard("室外气温", plcData.getTemperature() + ""  , "°C"));
        Date now = DateUtils.getNowDate();
        String start = sysConfigService.selectConfigByKey("sys.rest.heatDate");
        String year = sysConfigService.selectConfigByKey("sys.heat.year");
        Date startDate = DateUtils.parseDate(year + "-" + start);
        //累计耗热量
        list.add(new DataBoard("累计耗热量", sysBuildingService.selectTotalHeatQuantity(deptId, startDate, now).toString(), "kWh"));
        return success(list);
    }


    @GetMapping("/alarm/{deptId}")
    public AjaxResult list(@PathVariable("deptId") Long deptId){
        SysAlarm alarm = new SysAlarm();
        alarm.setDeptId(deptId);
        alarm.setLimit(20);
        return success(sysAlarmService.selectSysAlarmList(alarm));
    }


    @GetMapping("/house/{deptId}")
    public AjaxResult houseList(@PathVariable("deptId") Long deptId){
        return success(sysDeviceService.houseList(deptId));
    }

    @GetMapping("/building/{deptId}")
    public AjaxResult buildingList(@PathVariable("deptId") Long deptId){

        return success(sysDeviceService.buildingList(deptId, null, null)
                .stream().peek(buildingDataBoard -> {
                    DeviceCache heat = redisCache.getCacheObject(CacheConstants.IOT_DEVICE + buildingDataBoard.getHeatCode());
                    DeviceCache value = redisCache.getCacheObject(CacheConstants.IOT_DEVICE + buildingDataBoard.getValueCode());
//                    if (heat == null || heat.getHeatQuantity() == null){
//                        buildingDataBoard.setHeatQuantity(0.0);
//                    }else {
//                        buildingDataBoard.setHeatQuantity(heat.getHeatQuantity());
//                    }
                    if (value == null || value.getTempIndoor() == null){
                        buildingDataBoard.setTempIndoor(new BigDecimal("0"));
                    }else {
                        buildingDataBoard.setTempIndoor(value.getTempIndoor());
                    }
                }).collect(Collectors.toList())
        );
    }

    @GetMapping("/building/{deptId}/{housingId}/{buildNo}")
    public AjaxResult building(@PathVariable("deptId") Long deptId,
                                @PathVariable("housingId") Long housingId,
                                @PathVariable("buildNo") String buildNo){

        return success(sysDeviceService.buildingList(deptId, housingId, "-1".equals(buildNo)?null:buildNo)
                .stream().peek(buildingDataBoard -> {
                    DeviceCache heat = redisCache.getCacheObject(CacheConstants.IOT_DEVICE + buildingDataBoard.getHeatCode());
                    DeviceCache value = redisCache.getCacheObject(CacheConstants.IOT_DEVICE + buildingDataBoard.getValueCode());
//                    if (heat == null || heat.getHeatQuantity() == null){
//                        buildingDataBoard.setHeatQuantity(0.0);
//                    }else {
//                        buildingDataBoard.setHeatQuantity(heat.getHeatQuantity());
//                    }
                    if (value == null || value.getTempIndoor() == null){
                        buildingDataBoard.setTempIndoor(new BigDecimal("0"));
                    }else {
                        buildingDataBoard.setTempIndoor(value.getTempIndoor());
                    }
                    if (value == null || value.getValveOpening() == null){
                        buildingDataBoard.setValveOpening(0);
                    } else {
                        buildingDataBoard.setValveOpening(value.getValveOpening());
                    }
                    if (value == null || value.getHeatPower() == null){
                        buildingDataBoard.setHeatPower(0.0);
                    }else {
                        buildingDataBoard.setHeatPower(value.getHeatPower());
                    }

                }).collect(Collectors.toList())
        );
    }

    @GetMapping("/bottom")
    public AjaxResult bottom()
    {
        return success(sysDataBoardService.loadPlcData(getDeptId()));
    }

    /**
     * 储热量、电池比例
     * @return
     */
    @GetMapping("/bottom/temp")
    public AjaxResult temp()
    {
        GRMData plcData = sysDataBoardService.loadPlcData(getDeptId());
        //储热量 = 1.16 * 水箱容积 * ( 蓄热水箱温度 - 25 ) = 。。。。kwh
        BigDecimal heatQuantity = new BigDecimal("1.16").multiply(sysHousingService.totalTankVolume(getDeptId()))
                .multiply(BigDecimal.valueOf(plcData.getWaterTemperature()).subtract(new BigDecimal("25")));
        //保留两位小数
        heatQuantity = heatQuantity.setScale(2, RoundingMode.HALF_UP);
        //电池比例 = ( 蓄热水箱温度 - 25 ) / 25 * 100%
        BigDecimal batteryRatio = BigDecimal.valueOf(plcData.getWaterTemperature()).subtract(new BigDecimal("25"))
                .divide(new BigDecimal("25"), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
        return success(new DataBoard[]{
                new DataBoard("储热量", heatQuantity.toString(), "kWh"),
                new DataBoard("电池比例", batteryRatio.toString(), "%"),
        });
    }

    @GetMapping("/data/{deptId}")
    public AjaxResult data(@PathVariable("deptId") Long deptId){
        List<SysDataBoard> list = sysDataBoardService.statistics(deptId, 7);
        //数据倒序
        list.sort(Comparator.comparing(SysDataBoard::getInDate));
        return success(list);
    }

    @PostMapping("/test")
    public AjaxResult test(@RequestBody JSONObject jsonObject){
        log.info(jsonObject.toJSONString());
        return success(jsonObject);
    }
}
